<?php
/* SVN FILE: $Id: tools.php 255 2009-12-22 06:45:47Z supersmashbrothers $ */
/**
* ibMarket 2
* IP.Board 3.0
* Plugin Tools
*
* @author $Author: supersmashbrothers $
* @copyright $Copyright$
* @version $Revision: 255 $
* @lastrevision $Date: 2009-12-22 06:45:47 +0000 (Tue, 22 Dec 2009) $
* @modifiedby $LastChangedBy: supersmashbrothers $
* @lastmodified $LastChangedDate: 2009-12-22 06:45:47 +0000 (Tue, 22 Dec 2009) $
* @filesource $URL: http://ipb-ibmarket.googlecode.com/svn/ibmarket2/trunk/admin/applications_addon/other/ibmarket/modules_admin/plugin/tools.php $
*/


if ( ! defined( 'IN_ACP' ) )
{
	print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded 'admin.php'.";
	exit();
}

class admin_ibmarket_plugin_tools extends ipsCommand
{
	/**
	 * Main class entry point
	 *
	 * @access	public
	 * @param	object		ipsRegistry reference
	 * @return	void		[Outputs to screen]
	 */
	public function doExecute( ipsRegistry $registry )
	{
		if( ! IN_DEV )
		{
			$this->registry->output->showError($this->lang->words['cannot_find_plugin']);
		}
		
		$this->registry->getClass('class_localization')->loadLanguageFile( array( 'admin_market', 'admin_plugins' ) );
		
		$redirect = array(
							'skin' => "exportSkinXML",
							'lang' => "exportLangXML",
							'task' => "exportTaskXML",
						);
		if(!isset($redirect[$this->request['do']]))
		{
			$this->registry->output->showError($this->lang->words['no_permission']);
		}
		$function = $redirect[$this->request['do']];
		$this->$function();
	}
	
	private function exportSkinXML()
	{
		require_once( IPS_ROOT_PATH . 'sources/classes/skins/skinFunctions.php' );
		$this->skinFunctions = new skinFunctions( $this->registry );
		
		$setID = 0;
		$setOnly = TRUE;
		
		$setData = $this->skinFunctions->fetchSkinData( $setID );
		
		foreach($this->caches['market_plugin'] as $plugin)
		{
			$xml = $this->createPluginSkinXML( $plugin['directory'], $setID, $setOnly );
			
			//-----------------------------------------
			// Attempt to write...
			//-----------------------------------------
			
			/* Set file name */
			$file = IPSLib::getAppDir('ibmarket') . '/plugins/' . $plugin['directory'] . '/xml/' . $setData['set_key'] . '_templates.xml';
			
			/* Attempt to unlink first */
			@unlink( $file );
			
			if ( $xml )
			{
				if ( file_exists( $file ) AND ! IPSLib::isWritable( $file ) )
				{
					return FALSE;
				}
				
				file_put_contents( $file, $xml );
			}
		}
		
		$this->registry->output->silentRedirectWithMessage( $this->settings['base_url']."module=plugin" );
	}
	
	private function createPluginSkinXML($plugin, $setID=0, $setOnly=TRUE)
	{
		//-----------------------------------------
		// INIT
		//-----------------------------------------
		
		$templateGroups = array();
		
		//-----------------------------------------
		// XML
		//-----------------------------------------
		
		$infoXML = IPSLib::getAppDir('ibmarket') . '/plugins/' . $plugin . '/xml/information.xml';
		
		if ( ! file_exists( $infoXML ) )
		{
			return FALSE;
		}
		
		require_once( IPS_KERNEL_PATH.'classXML.php' );
		$xml = new classXML( IPS_DOC_CHAR_SET );
		
		//-----------------------------------------
		// Get information file
		//-----------------------------------------
		
		$xml->load( $infoXML );
		
		foreach( $xml->fetchElements( 'template' ) as $template )
		{
			$name  = $xml->fetchItem( $template );
			$match = $xml->fetchAttribute( $template, 'match' );
			
			if ( $name )
			{
				$templateGroups[ $name ] = $match;
			}
		}
		
		if ( ! is_array( $templateGroups ) OR ! count( $templateGroups ) )
		{
			return FALSE;
		}
		
		//-----------------------------------------
		// Fetch templates
		//-----------------------------------------
		
		if ( $setOnly === TRUE AND $setID > 0 )
		{
			$this->DB->build( array( 'select' => '*',
									 'from'   => 'skin_templates',
									 'where'  => 'template_set_id=' . $setID ) );
			
			$this->DB->execute();
			
			while( $row = $this->DB->fetch() )
			{
				$templates[ $row['template_group'] ][ strtolower( $row['template_name'] ) ] = $row;
			}
		}
		else
		{
			$_templates = $this->skinFunctions->fetchTemplates( $setID );
			
			/* Remove set 0 templates */
			if ( $setID > 0 )
			{
				if ( is_array( $_templates ) AND count( $_templates ) )
				{
					foreach( $_templates as $group => $data )
					{
						foreach( $data as $name => $templateData )
						{
							if ( $templateData['template_set_id'] > 0 )
							{
								$templates[ $group ][ $name ] = $templateData;
							}
						}
					}
				}
			}
			else
			{
				$templates = $_templates;
			}
		}
		
		//-----------------------------------------
		// Loop through...
		//-----------------------------------------
		
		$xml->newXMLDocument();
		$xml->addElement( 'templates', '', array( 'application' => $app, 'templategroups' => serialize( $templateGroups ) ) );
		
		if ( ! is_array( $templates ) OR ! count( $templates ) )
		{
			return FALSE;
		}
		
		$added   = 0;
		
		foreach( $templates as $group => $data )
		{
			$_okToGo = FALSE;
			
			foreach( $templateGroups as $name => $match )
			{
				if ( $match == 'contains' )
				{
					if ( stristr( $group, $name ) )
					{
						$_okToGo = TRUE;
						break;
					}
				}
				else if ( $group == $name )
				{
					$_okToGo = TRUE;
				}
			}
			
			if ( $_okToGo === TRUE )
			{
				$xml->addElement( 'templategroup', 'templates', array( 'group' => $group ) );
				
				foreach( $data as $name => $templateData )
				{
					unset( $templateData['theorder'] );
					unset( $templateData['template_id'] );
					unset( $templateData['template_set_id'] );
					unset( $templateData['template_added_to'] );
					
					$xml->addElementAsRecord( 'templategroup', 'template', $templateData );
					$added++;
				}
			}
		}
		
		if ( ! $added )
		{
			return FALSE;
		}
		
		return $xml->fetchDocument();
	}
	
	private function createLanguageXML($plugin, $lang_id)
	{
		//-----------------------------------------
		// Init
		//-----------------------------------------
		
		$_name			= 'language_pack.xml';
		$LATESTVERSION	= IPSLib::fetchVersionNumber();
		
		//-----------------------------------------
		// Filter
		//-----------------------------------------
		
		$_where	= " AND word_app='ibmarket' AND word_pack LIKE '".$plugin."_%'";
		$doPack	= false;
		
		//-----------------------------------------
		// Create the XML library
		//-----------------------------------------
		
		require_once( IPS_KERNEL_PATH.'classXML.php' );
		$xml = new classXML( IPS_DOC_CHAR_SET );
		$xml->newXMLDocument();
		$xml->addElement( 'languageexport' );
		$xml->addElement( 'languagegroup', 'languageexport' );
		
		//-----------------------------------------
		// Get language pack
		//-----------------------------------------
		
		$data = $this->DB->buildAndFetch( array( 'select' => '*', 'from' => 'core_sys_lang', 'where' => "lang_id={$lang_id}" ) );
		
		//-----------------------------------------
		// Add pack if necessary
		//-----------------------------------------
		
		if( $doPack )
		{
			$xml->addElementAsRecord( 'languagegroup', 'langinfo', $data );
		}
		
		//-----------------------------------------
		// Get the words
		//-----------------------------------------
		
		$this->DB->build( array( 'select' => '*', 'from' => 'core_sys_lang_words', 'where' => "lang_id={$lang_id}" . $_where ) );
		$this->DB->execute();
		
		//-----------------------------------------
		// Add words to export
		//-----------------------------------------
		
		$word_packs = array();
		
		while( $r = $this->DB->fetch() )
		{
			$content = array();
			
			$content = array( 
							'word_app'				=> $r['word_app'],
							'word_pack'				=> $r['word_pack'],
							'word_key'				=> $r['word_key'],
							'word_default'			=> stripslashes( $r['word_default'] ),
							'word_custom'			=> stripslashes( $r['word_custom'] ),
							'word_default_version'	=> ( $r['word_default_version'] >= 30000 ) ? $r['word_default_version'] : $LATESTVERSION['long'],
							'word_custom_version'	=> $r['word_custom_version'],
							'word_js'				=> $r['word_js']
						);
			
			$xml->addElementAsRecord( 'languagegroup', 'lang', $content );
		}
		
		$file = IPSLib::getAppDir('ibmarket').'/plugins/'.$plugin.'/xml/language_pack.xml';
		/* Attempt to unlink first */
		@unlink( $file );
		
		if ( file_exists( $file ) AND ! IPSLib::isWritable( $file ) )
		{
			return;
		}
		
		file_put_contents( $file, $xml->fetchDocument() );
	}
	
	private function exportLangXML()
	{
		foreach($this->caches['market_plugin'] as $plugin)
		{
			$this->createLanguageXML( $plugin['directory'], 1 );
		}
		
		$this->registry->output->silentRedirectWithMessage( $this->settings['base_url']."module=plugin" );
	}
	
	private function createTasksXML($plugin)
	{
		//-----------------------------------------
		// Init
		//-----------------------------------------
		
		$_name			= 'tasks.xml';
		
		//-----------------------------------------
		// Filter
		//-----------------------------------------
		
		$infoXML = IPSLib::getAppDir('ibmarket') . '/plugins/' . $plugin . '/xml/information.xml';
		
		if ( ! file_exists( $infoXML ) )
		{
			return FALSE;
		}
		
		require_once( IPS_KERNEL_PATH.'classXML.php' );
		$xml = new classXML( IPS_DOC_CHAR_SET );
		$xml->load( $infoXML );
		
		$taskKeys = array();
		foreach( $xml->fetchElements( 'tasks' ) as $language )
		{
			$taskKeys[] = $xml->fetchItem( $taskKeys );
		}
		
		if ( ! count( $taskKeys ) )
		{
			return FALSE;
		}
		
		$_where	= '';
		
		$_c  = 0;
		$xml->newXMLDocument();
		$xml->addElement( 'export' );
		$xml->addElement( 'group', 'export' );
		
		/* Query tasks */
		$this->DB->build( array( 'select' => '*', 'from' => 'task_manager', 'where' => "task_key IN ('".implode("', '",$taskKeys)."')" ) );		
		$this->DB->execute();
		
		/* Loop through and add tasks to XML */
		while ( $r = $this->DB->fetch() )
		{
			$_c++;
			$xml->addElementAsRecord( 'group', 'row', $r );
		}
		
		/* Finish XML */	
		$doc = $xml->fetchDocument();
		
		$file = IPSLib::getAppDir('ibmarket').'/plugins/'.$plugin.'/xml/tasks.xml';
		/* Attempt to unlink first */
		@unlink( $file );
		
		if ( file_exists( $file ) AND ! IPSLib::isWritable( $file ) )
		{
			return;
		}
		
		if(!$_c || !$doc)
		{
			return;
		}
		
		file_put_contents( $file, $doc );
	}
	
	private function exportTaskXML()
	{
		foreach($this->caches['market_plugin'] as $plugin)
		{
			$this->createTasksXML( $plugin['directory'] );
		}
		
		$this->registry->output->silentRedirectWithMessage( $this->settings['base_url']."module=plugin" );
	}
}